package com.huiminpay.merchant.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectRequest;
import com.huiminpay.common.cache.domain.BusinessException;
import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.merchant.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
public class FileServiceImpl implements FileService {
    @Autowired
    private OSS oss;
    @Value("${oss.aliyun.bucket}")
    private String bucketName;
    @Value("${oss.aliyun.domain}")
    private String domain;

    @Override
    public String upload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String ext = originalFilename.substring(originalFilename.indexOf("."));
        String fileName=System.currentTimeMillis()+ext;
        try {
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName,fileName,file.getInputStream());
            oss.putObject(putObjectRequest);
        } catch (IOException e) {
            throw new BusinessException(CommonErrorCode.E_100106);
        }
        return domain+fileName;

    }
}
